using UnityEngine;

namespace ViewController.Gameplay
{
    public class Trigger2DCheck : MonoBehaviour
    {
        public int enterCount;

        /// <summary>
        ///     使用 LayerMask 可以在 Inspector 配置想要触发碰撞的 Layer
        /// </summary>
        public LayerMask targetLayers;

        public bool Triggered => enterCount > 0;

        private void OnTriggerEnter2D(Collider2D other)
        {
            if (IsInLayerMask(other.gameObject, targetLayers)) enterCount++;
        }

        private void OnTriggerExit2D(Collider2D other)
        {
            if (IsInLayerMask(other.gameObject, targetLayers)) enterCount--;
        }

        /// <summary>
        ///     LayerMask 中是否包含我想要的 Layer
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="layerMask"></param>
        /// <returns></returns>
        private bool IsInLayerMask(GameObject obj, LayerMask layerMask)
        {
            // 根据 Layer 数值进行移位获得用于运算的 Mask 值
            var objLayerMask = 1 << obj.layer;
            return (layerMask.value & objLayerMask) > 0;
        }
    }
}